/*
 * @Descripttion: 
 * @Author: cuidm
 * @Date: 2022-08-08 13:35:23
 * @LastEditors: cuidm
 * @LastEditTime: 2022-09-22 09:48:25
 */
import React, { useState, useEffect } from "react";
import { Modal, Form, Button, Input,  message, Space, Tooltip, Radio, Select, Row, Col } from "antd";
import cmdbres from "@/data/cmdbres";
import request from "@/utils/request";
import regexpUtil from "@/utils/regexpUtil";
import hcpUtils from "@/utils/hcpUtils";

const user = hcpUtils.getUser();
const {filterArray} = hcpUtils;
const CreateServiceInstanc = ({info, visible, setVisible, onCreateFinish})  => {
	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false);
	const [type, setType] = useState("0");
    const [moduleData, setModuleData] = useState([]);
	const [bigCategoryData, setBigCategory] = useState([]);
    const [smallCategoryData, setSmallCategory] = useState([]);
	useEffect(() => {
        if(visible && info?.bizId) {
            queryServiceTemplateList();
            getCategoryData();
        }
    }, [visible]);


    const queryServiceTemplateList = async (params = { current: 1, pageSize: 10000000 }) => {
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryServiceTemplateList,
                data: {
                    bizId: info.bizId,
                    pageSize: params.pageSize,
                    pageNumber: params.current,
                },
            });
            setLoading(false);
            if (res && res.data) {
                setModuleData(res.data);
            } else {
                setModuleData([]);
            }
        } catch (error) {
            console.log(error);
        } 
    };

    const getCategoryData = async () => {
        try {
            const res = await request({
                ...cmdbres.queryServiceCategory,
                params: {
                    bizId: info.bizId,
                },
            });
            if (res && res.data && res.data.info) {
                const arr = filterArray(res.data.info);
                setBigCategory(arr);
                if(info && info.id) {
                    initUpdateData(arr);
                }
            } else {
                setBigCategory([]);
            }
        } catch (error) {
            console.log(error);
        } 
    };

    const initUpdateData = (arr) => {
        if(!(arr && arr.length)) return;
        let big = null;
        let small = null;
        arr.map(item => {//仅支持二级
            item?.children?.map(child=> {
                if(child.id == info.serviceCategoryId) {
                    small = child;
                    big = item;
                }
            })
        });
        
        console.log(arr, big, small)
        form.setFieldsValue({
            name: info.name,
            bigCategory: big?.id,
            smallCategory: small?.id
        })
        setSmallCategory(big?.children??[]);
    }

    const onFinish = async (values) => {
		setLoading(true);
		let param = {
			serviceInstanceName: values.serviceInstanceName,
			bizId: info.bizId,
			setId: info.instanceId,
			createType: values.createType,
			serviceTemplateId: values.createType == "0" ? values.serviceTemplateId : 0,
			author: user.staffName
		}
		let res = await request({
			...cmdbres.createServiceInstance,
			data: param
		});
		setLoading(false);
		if (res && res.code == 200) {
			setVisible(false);
			message.success(`新建模块成功！`);
			if (typeof onCreateFinish == "function") onCreateFinish(res);
		}
	};

	const onCancel = () => {
		setVisible(false);
	}

	return (
		<Modal
			title="新建模块"
			className="hcp-modal-sm"
			visible={visible}
			footer={null}
			onCancel={onCancel}
			destroyOnClose
			maskClosable={false}
			afterClose={()=>{form.resetFields()}}
		>
			<Form
				form={form}
				labelCol={{ span: 5 }}
				wrapperCol={{ span: 18 }}
				name="basic"
				onFinish={onFinish}
                initialValues={{
                    createType: "0"
                }}
			>
				<Form.Item label="已选择">
					<span>{info?.instanceName??'-'}</span>
				</Form.Item>
				<Form.Item label="创建类型" name="createType">
					<Radio.Group
						style={{ width: '100%', marginBottom: 10 }}
						buttonStyle="solid"
						onChange={(e)=> {
                            form.setFieldsValue({
                                serviceTemplateId: undefined,
                                bigCategory: undefined,
                                smallCategory: undefined,
                                serviceInstanceName: undefined
                            });
                            setType(e.target.value);
                        }}
						value={type}
					>
						<Radio.Button value="0">
							从模板新建
						</Radio.Button>
						<Radio.Button value="1">
							直接新建
						</Radio.Button>
					</Radio.Group>
				</Form.Item>
				{
					type == "0" && <Form.Item
						label="服务模板"
                        name="serviceTemplateId"
						rules={[
							{
								required: true,
								message: '请选择服务模板',
							},
						]}
					>
						<Select
							placeholder="请选择"
							name="moduleGroup"
							style={{ width: "100%", marginRight: 10 }}
							getPopupContainer={(triggerNode) =>
								triggerNode.parentElement
							}
							onChange={(value, option)=>{form.setFieldsValue({serviceInstanceName: option.label})}}
						>
							{
								moduleData.map((item, index) => (
									<Select.Option
										key={item.id}
										value={item.id}
                                        label={item.name}
									>
										{item.name}
									</Select.Option>
								))
							}
						</Select>
					</Form.Item>
				}
				<Form.Item 
					label={
						<span>模块名称
							{type=="0" && <Tooltip title="模块名称需同服务模板名称保持一致"><i className="iconfont icon-question"></i></Tooltip>}
						</span>
					}
					name="serviceInstanceName"
					rules={[ { required: true, message: '请输入集群名称'}]}
				>
					<Input placeholder="请输入集群名称" maxLength={256} readOnly={type=="0"}/>
				</Form.Item>
				{type=='1'&&<Form.Item 
                    label="服务分类 "
                    required
                >
                    <Row gutter={[20, 20]}>
                        <Col span={12}>
                        <Form.Item 
                            name="bigCategory"
                            rules={[{required: true,message: '请选择一级分类'}]}
                        >
                            <Select
                                placeholder="请选择"
                                style={{ width: "100%", marginRight: 10 }}
                                onChange={(value, option) => {
                                    setSmallCategory(option.relation.children||[]);
                                    form.setFieldsValue({smallCategory: undefined});
                                }}
                                showSearch
                            >
                                {
                                    bigCategoryData?.map((item, index) => (
                                        <Select.Option
                                            key={item.id}
                                            value={item.id}
                                            relation={item}
                                        >
                                            {item.name}
                                        </Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                        </Col>
                        <Col span={12}>
                        <Form.Item 
                            name="smallCategory"
                            rules={[{required: true,message: '请选择二级分类'}]}
                        >
                            <Select
                                placeholder="请选择"
                                style={{ width: "100%", marginRight: 10 }}
                                onChange={(value, option) => {

                                }}
                                showSearch
                            >
                                {
                                    smallCategoryData?.map((item, index) => (
                                        <Select.Option
                                            key={item.id}
                                            value={item.id}
                                            relation={item}
                                        >
                                            {item.name}
                                        </Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                        </Col>
                    </Row>
                </Form.Item>}
				<div className="hcp-modal-body-footer">
					<Form.Item wrapperCol={{ span: 24 }} >
						<Button onClick={onCancel}>取消</Button>
						<Button type="primary" htmlType="submit" loading={loading}>提交</Button>
					</Form.Item>
				</div>
			</Form>
		</Modal>
	)
}

export default CreateServiceInstanc;
